//
//  UserDetailHeaderView.swift
//  todaySwift
//
//  Created by ChokWah on 2018/3/24.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import UIKit
import IBAnimatable
import Kingfisher
import SwiftTheme

class UserDetailHeaderView: UIView, NibLoadable {
    
    // 动态页面数据
    var dongtais = [UserDetailDongtai]() {
        didSet {
            
        }
    }
    
    // MARK: 设置模型时对UIView进行赋值，刷新
    var userDetail: UserDetail? {
        didSet {
            backgroundImageView.kf.setImage(with: URL(string: userDetail!.bg_img_url))
            avatarImageView.kf.setImage(with: URL(string: userDetail!.avatar_url))
            vImageView.isHidden = !userDetail!.user_verified
            nameLabel.text = userDetail!.name
            if userDetail!.verified_agency == "" {
                verifiedAgencyLabelHeight.constant = 0
                verifiedAgencyLabelTop.constant = 0
            }else {
                verifiedAgencyLabel.text = userDetail!.verified_agency + ": "
                verifiedContentLabel.text = userDetail!.verified_content
            }
            concernButton.isSelected = userDetail!.is_following
            concernButton.theme_backgroundColor = userDetail!.is_following ? "colors.userDetailFollowingConcernBtnBgColor" : "colors.userDetailConcernBtnBgColor"
            concernButton.borderColor = userDetail!.is_following ? .grayColor232() : .globalRedColor()
            concernButton.borderWidth = userDetail!.is_following ? 1 : 0
            if userDetail!.area == "" {
                areaButton.isHidden = true
                areaButtonHeight.constant = 0
                areaButtonTop.constant = 0
            }else {
                areaButton.setTitle(userDetail!.area, for: .normal)
            }
            descriptionLabel.text = userDetail!.description
            if userDetail!.descriptionHeight > 21 {
                unfoldButton.isHidden = false
                unfoldButtonWidth.constant = 40
            }
            // 推荐按钮的约束设置
            self.recommendButtonWidth.constant = 0 // 不显示
            self.recommendButtonTrailing.constant = 10
            followingCountLabel.text = String(userDetail!.followings_count)
            followerCountLabel.text = String(userDetail!.followers_count)
            // 动态里的详情：文章，视频之类
            if userDetail!.top_tab.count > 0 {
                // 添加按钮和 tableView
                for (index, topTab) in userDetail!.top_tab.enumerated() {
                    let button = UIButton(frame: CGRect(x: CGFloat(index) * topTabButtonWidth, y: 0, width: topTabButtonWidth, height: scrollView.height))
                    button.setTitle(topTab.show_name, for: .normal)
                    button.tag = index
                    button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
                    button.theme_setTitleColor("colors.black", forState: .normal)
                    button.theme_setTitleColor("colors.globalRedColor", forState: .selected)
                    button.addTarget(self, action: #selector(topTabButtonClicked), for: .touchUpInside)
                    scrollView.addSubview(button)
                    if index == 0 {
                        button.isSelected = true
                        privateButton = button // 先赋值给弱引用的button属性
                    }
                    if index == userDetail!.top_tab.count - 1 { // 最后一个
                        scrollView.contentSize = CGSize(width: button.frame.maxX, height: scrollView.height)
                    }
                    let tableview = UITableView(frame: CGRect(x: CGFloat(index) * screenWidth, y: 0, width: screenWidth, height: scrollView.height))
                    tableview.cwc_registerCell(cell: UserDetailDongTaiCell.self)
                    tableview.delegate = self
                    tableview.dataSource = self
                    tableview.rowHeight = 130
                    scrollView.addSubview(tableview)
                }
                scrollView.addSubview(indicatorView)
            }else {
                tapTabViewHeight.constant = 0
                tapTabView.isHidden = true
            }
            layoutIfNeeded()
        }
    }
    
    // MARK: xib属性
    // topTab 指示条
    lazy var indicatorView : UIView = {
        let indicatorView = UIView(frame: CGRect(x: (topTabButtonWidth - topTabindicatorWidth) * 0.5, y: self.tapTabView.height - 3, width: topTabindicatorWidth, height: topTabindicatorHeight))
        indicatorView.theme_backgroundColor = "colors.globalRedColor"
       return indicatorView
    }()
    weak var privateButton = UIButton()
    // 背景图片 imageview
    @IBOutlet weak var backgroundImageView: UIImageView!
    @IBOutlet weak var backgroundImageViewTop: NSLayoutConstraint!
    // 推荐View
    @IBOutlet weak var recommendView: UIView!
    @IBOutlet weak var recommendViewHeight: NSLayoutConstraint!
    // 推荐 button
    @IBOutlet weak var recommendButton: AnimatableButton!
    @IBOutlet weak var recommendButtonTrailing: NSLayoutConstraint!
    @IBOutlet weak var recommendButtonWidth: NSLayoutConstraint!
    // 关注 button
    @IBOutlet weak var concernButton: AnimatableButton!
    // 发私信 button
    @IBOutlet weak var sendMailButton: UIButton!
    // 头条号图片
    @IBOutlet weak var toutiaohaoImageView: UIImageView!
    // 名字 Label
    @IBOutlet weak var nameLabel: UILabel!
    // 右下角vip图片 imageview
    @IBOutlet weak var vImageView: UIImageView!
    // 头像图片 imageview
    @IBOutlet weak var avatarImageView: AnimatableImageView!
    // 头条认证Label
    @IBOutlet weak var verifiedAgencyLabel: UILabel!
    @IBOutlet weak var verifiedAgencyLabelHeight: NSLayoutConstraint!
    @IBOutlet weak var verifiedAgencyLabelTop: NSLayoutConstraint!
    // 认证内容 Label
    @IBOutlet weak var verifiedContentLabel: UILabel!
    // 地区 Button
    @IBOutlet weak var areaButton: UIButton!
    @IBOutlet weak var areaButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var areaButtonTop: NSLayoutConstraint!
    // 描述内容
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var descriptionLabelHeight: NSLayoutConstraint!
    // 展开 Button
    @IBOutlet weak var unfoldButton: UIButton!
    @IBOutlet weak var unfoldButtonWidth: NSLayoutConstraint!
    @IBOutlet weak var unfoldButtonTrailing: NSLayoutConstraint!
    // 关注数量 Label
    @IBOutlet weak var followingCountLabel: UILabel!
    // 粉丝数量 Label
    @IBOutlet weak var followerCountLabel: UILabel!
    // 文章，视频，问答
    @IBOutlet weak var tapTabView: UIView!
    @IBOutlet weak var tapTabViewHeight: NSLayoutConstraint!
    @IBOutlet weak var separatorView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    // 底层 View
    @IBOutlet weak var baseView: UIView!
    @IBOutlet weak var bottomScrollView: UIScrollView!
    // 自定义的推荐View
    fileprivate lazy var relationRecommendView: RelationRecommendView = {
       let relationRecommendView = RelationRecommendView.loadViewFromNib()
        return relationRecommendView
    }()
    
    // MARK: 重写方法
    override func awakeFromNib() {
        super.awakeFromNib()
        concernButton.setTitle("关注", for: .normal)
        concernButton.setTitle("已关注", for: .selected)
        
        // 设置主题颜色
        theme_backgroundColor = "colors.cellBackgroundColor"
        baseView.theme_backgroundColor = "colors.cellBackgroundColor"
        avatarImageView.layer.theme_borderColor = "colors.cellBackgroundColor"
        tapTabView.theme_backgroundColor = "colors.cellBackgroundColor"
        separatorView.theme_backgroundColor = "colors.separatorViewColor"
        nameLabel.theme_textColor = "colors.black"
        sendMailButton.theme_setTitleColor("colors.userDetailSendMailTextColor", forState: .normal)
        unfoldButton.theme_setTitleColor("colors.userDetailSendMailTextColor", forState: .normal)
        followerCountLabel.theme_textColor = "colors.userDetailSendMailTextColor"
        followingCountLabel.theme_textColor = "colors.userDetailSendMailTextColor"
        concernButton.theme_setTitleColor("colors.userDetailConcernButtonTextColor", forState: .normal)
        concernButton.theme_setTitleColor("colors.userDetailConcernButtonSelectedTextColor", forState: .selected)
        verifiedAgencyLabel.theme_textColor = "colors.verifiedAgencyTextColor"
        verifiedContentLabel.theme_textColor = "colors.black"
        descriptionLabel.theme_textColor = "colors.black"
        descriptionLabel.theme_textColor = "colors.black"
        toutiaohaoImageView.theme_image = "images.toutiaohao"
        areaButton.theme_setTitleColor("colors.black", forState: .normal)
    }
    
    fileprivate func resetLayout() {
        baseView.height = tapTabView.frame.maxY
        height = baseView.frame.maxY
    }
}

// MARK: 所有的点击方法
extension UserDetailHeaderView {
    
    // 动态内按钮点击：文章，视频之类
    @objc func topTabButtonClicked(button: UIButton) {
        // 判断是哪个button事件
        privateButton?.isSelected = false
        button.isSelected = !button.isSelected
        UIView.animate(withDuration: 0.25, animations: {
            self.indicatorView.centerX = button.centerX
            self.bottomScrollView.contentOffset = CGPoint(x: CGFloat(button.tag) * screenWidth, y: 0)
        }) { (_) in
            self.privateButton = button
        }
    }
    
    // 发私信按钮点击
    @IBAction func sendMailButtonAction(_ sender: Any) {
    }
    // 关注按钮点击
    @IBAction func concernButtonAction(_ sender: AnimatableButton) {
        //        sender.isSelected = !sender.isSelected
        if sender.isSelected { // 已经关注，执行取消关注
            NetWorkTool.relationUnfollow(user_id: userDetail!.user_id, completionHandler: { (_) in
                sender.isSelected = !sender.isSelected
                self.concernButton.theme_backgroundColor = "colors.globalRedColor"
                self.recommendButton.isHidden = true
                self.recommendButtonWidth.constant = 0 // 不显示
                self.recommendButton.isSelected = false
                self.recommendButtonTrailing.constant = 0
                self.recommendViewHeight.constant = 0
                UIView.animate(withDuration: 0.25, animations: {
                    self.recommendButton.transform = .identity
                    self.layoutIfNeeded()
                }, completion: { (_) in
                    self.resetLayout()
                })
            })
        }else {                      // 未关注，执行关注事件
            NetWorkTool.relationFollow(user_id: userDetail!.user_id, completionHandler: { (_) in
                sender.isSelected = !sender.isSelected
                self.concernButton.theme_backgroundColor = "colors.userDetailFollowingConcernBtnBgColor"
                self.recommendButton.isHidden = false
                self.recommendButton.isSelected = false
                self.recommendButtonWidth.constant = 28.0 // 不显示
                self.recommendButtonTrailing.constant = 15
                self.recommendViewHeight.constant = 233
                UIView.animate(withDuration: 0.25, animations: {
                    self.recommendButton.transform = .identity
                    self.layoutIfNeeded()
                }, completion: { (_) in
                    self.resetLayout()
                    // 点击了关注，出现于关注推荐数据
                    NetWorkTool.supplementRecommends(user_id: self.userDetail!.user_id, completionHandler: { (userCards) in
                        self.recommendView.addSubview(self.relationRecommendView)
                        self.relationRecommendView.userCards = userCards
                    })
                })
            })
        }
    }
    // 推荐关注按钮点击
    @IBAction func reCommendButtonAction(_ sender: AnimatableButton) {
        sender.isSelected = !sender.isSelected
        recommendViewHeight.constant = sender.isSelected ? 0 : 223 // 如果选中则展开推荐关注view
        UIView.animate(withDuration: 0.25, animations: {
            sender.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(sender.isSelected ? Double.pi : 0))
            self.layoutIfNeeded()
        }) { (_) in
            self.resetLayout()
        }
    }
    // 展开详情按钮点击
    @IBAction func unfoldButtonAction(_ sender: Any) {
        unfoldButton.isHidden = true
        unfoldButtonWidth.constant = 0
        relationRecommendView.labelHeight.constant = 0
        relationRecommendView.layoutIfNeeded()
        descriptionLabelHeight.constant = userDetail!.descriptionHeight
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
        }) { (_) in
            self.resetLayout()
        }
    }
}


// MARK: TableView的代理方法
extension UserDetailHeaderView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.cwc_dequeueReusableCell(indexPath: indexPath) as UserDetailDongTaiCell
        cell.dongtai = dongtais[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dongtais.count
    }
    
    
}

